package dao

import (
	"context"
	"inventory/internal/constant"
	"inventory/pkg/ecode"
	"time"

	"inventory/internal/model"
)

// GetInventoryOrder 获取盘点单
func (d *Dao) GetInventoryOrder(ctx context.Context, warehouseID int, orderNumber string) (inventory *model.InventoryOrder, err error) {
	inventory = &model.InventoryOrder{}
	err = d.TransContext(ctx).Model(&model.InventoryOrder{}).Where("warehouse_id = ? and order_number = ?", warehouseID, orderNumber).Take(&inventory).Error
	if err != nil {
		err = d.processSqlError(err)
	}
	return
}

// FindInventoryOrderDetails 获取盘点详情
func (d *Dao) FindInventoryOrderDetails(ctx context.Context, orderID uint64) (details []*model.InventoryDetail, err error) {
	err = d.TransContext(ctx).Model(&model.InventoryDetail{}).Where("order_id = ?", orderID).Find(&details).Error
	if err != nil {
		err = d.processSqlError(err)
	}
	return
}

// DeleteAllInventoryDraftByOrderID 删除所有盘点草稿根据orderID
func (d *Dao) DeleteAllInventoryDraftByOrderID(ctx context.Context, orderID uint64) (err error) {
	err = d.TransContext(ctx).Where("order_id = ?", orderID).Delete(model.InventoryDetail{}).Error
	if err != nil {
		err = d.processSqlError(err)
	}
	return
}

// FindInventoryOrders 获取盘点单列表
func (d *Dao) FindInventoryOrders(ctx context.Context, sgID, warehouseID uint32, startDate, endDate time.Time,
	pageNo, pageSize int, queryOrderNumber string) (total int64, orders []*model.InventoryOrder, err error) {
	db := d.TransContext(ctx).Model(&model.InventoryOrder{}).Where(
		"sg_id = ? and create_time between ? and ?  and status != ? and warehouse_id = ?",
		sgID, startDate, endDate.Add(time.Hour*24-time.Second), constant.InventoryOrderCanceled, warehouseID)
	if queryOrderNumber != "" {
		if len(queryOrderNumber) < 4 {
			err = ecode.BadRequest("单号模糊搜索至少需要4位数字")
		}
		db = db.Where("order_number like ?", "%"+queryOrderNumber+"%")
	}
	if err = db.Count(&total).Error; err != nil {
		err = d.processSqlError(err)
		return
	}
	err = db.Order("id desc").Offset((pageNo - 1) * pageSize).Limit(pageSize).Find(&orders).Error
	if err != nil {
		err = d.processSqlError(err)
	}
	return
}

// UpdateInventoryDetailByOrderID 根据orderID更新详情
func (d *Dao) UpdateInventoryDetailByOrderID(ctx context.Context, orderID uint64, updateMap map[string]interface{}) (err error) {
	return d.processSqlError(d.TransContext(ctx).Model(&model.InventoryDetail{}).Where(
		"order_id = ?", orderID).Updates(updateMap).Error)
}
